package cn.zyjblogs.config.security;

import cn.zyjblogs.server.user.po.OauthUserDetails;
import cn.zyjblogs.starter.common.entity.constant.ContextKeyConstant;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * jwt内容增强器
 *
 * @author zhuyijun
 */
@Component
public class JwtTokenEnhancer implements TokenEnhancer {
    /**
     * token增强
     *
     * @param oAuth2AccessToken
     * @param authentication
     * @return org.springframework.security.oauth2.common.OAuth2AccessToken
     * @author zhuyijun
     * @date 2022/8/18 下午8:51
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication authentication) {
        OauthUserDetails authUser = (OauthUserDetails) authentication.getPrincipal();
        final Map<String, Object> additionalInfo = new HashMap<>(4);
        // 注意添加的额外信息，不能和已有的json对象中的key重名
        additionalInfo.put(ContextKeyConstant.USER_ID_KEY, authUser.getId());
        additionalInfo.put(ContextKeyConstant.USERNAME_KEY, authUser.getUsername());
        additionalInfo.put(ContextKeyConstant.NAME_KEY, authUser.getName());
        additionalInfo.put(ContextKeyConstant.TENANT_ID_KEY, authUser.getTenantId());
        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(additionalInfo);
        return oAuth2AccessToken;

    }
}
